package com.treasure.mall.zbqmallapi.controller.marketing;

import com.treasure.mall.biz.entity.marketing.RedPacketGrabLogPO;
import com.treasure.mall.biz.entity.marketing.RedPacketPO;
import com.treasure.mall.biz.entity.user.UserPO;
import com.treasure.mall.biz.service.core.marketing.RedPacketService;
import com.treasure.mall.zbq.common.annotation.CurrentUser;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbqmallapi.annotation.AccessControl;
import com.treasure.mall.zbqmallapi.vo.marketing.RedPacketGrabLogVO;
import com.treasure.mall.zbqmallapi.vo.marketing.RedPacketVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/8/3
 */
@RestController
@RequestMapping("/marketing/redPacket")
public class RedPacketController {
    @Autowired
    private RedPacketService redPacketService;

    /**
     * 当前启用的红包
     *
     * @param merchantId
     * @return
     */
    @GetMapping("/current")
    public ApiResult current(Long merchantId, @CurrentUser UserPO userPO) {
        RedPacketPO po = redPacketService.currentRedPacket(merchantId);

        if (po == null) {
            return ApiResult.error("当前没有可用的红包");
        }

        RedPacketVO vo = new RedPacketVO(po);
        if (userPO != null) {
            vo.setUserGrabbed(redPacketService.userGrabbed(vo.getId(), userPO.getUserId()));
        }

        return ApiResult.ok(vo);
    }

    /**
     * 抢红包
     *
     * @param userPO
     * @param redPacketId
     * @return
     */
    @PostMapping("/grab")
    @AccessControl(needLogin = true)
    public ApiResult grab(@CurrentUser UserPO userPO, Long redPacketId) {
        RedPacketGrabLogPO logPO = redPacketService.grab(redPacketId, userPO);

        return ApiResult.ok(new RedPacketGrabLogVO(logPO));
    }

    /**
     * 红包抢夺记录
     *
     * @param redPacketId
     * @return
     */
    @GetMapping("/grabLogs")
    public ApiResult grabLogs(Long redPacketId) {
        List<RedPacketGrabLogPO> pos = redPacketService.getGrabLogs(redPacketId);

        List<RedPacketGrabLogVO> vos = pos.stream()
                .map(RedPacketGrabLogVO::new).collect(Collectors.toList());

        return ApiResult.ok(vos);
    }
}
